<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :inline="true"
      :model="queryParams"
      label-width="68px"
      size="small"
    >
      <!-- <el-form-item label="设备ID" prop="equipmentID">
        <el-input v-model="queryParams.equipmentID" clearable placeholder="请输入设备ID" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="硬件号" prop="hardwareNumber">
        <el-input v-model="queryParams.hardwareNumber" clearable placeholder="请输入硬件号"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="链接状态" prop="status">
        <el-input v-model="queryParams.status" clearable placeholder="请输入链接状态" @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="所属门店" prop="type">
        <el-select
          v-model="queryParams.storeName"
          placeholder="请选择门店"
          style="width: 100%"
        >
          <el-option
            v-for="item in storeOptions"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeName"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="最后断开时间" label-width="100px">
        <el-date-picker
          v-model="dateRange"
          :default-time="['00:00:00', '23:59:59']"
          end-placeholder="结束日期"
          range-separator="-"
          start-placeholder="开始日期"
          style="width: 240px"
          type="daterange"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          icon="el-icon-search"
          size="mini"
          type="primary"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['machine:equipment:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['machine:equipment:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="green"
          style="color: white; background-color: green"
          @click="rapidAdd"
          >快速增加
        </el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button v-hasPermi="['machine:equipment:edit']" :disabled="single" icon="el-icon-edit" plain size="mini"
          type="success" @click="handleUpdate">修改
        </el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button v-hasPermi="['machine:equipment:remove']" :disabled="multiple" icon="el-icon-delete" plain
          size="mini" type="danger" @click="handleDelete">删除
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['machine:equipment:export']"
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          @click="handleExport"
          >导出
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      :header-cell-style="{ background: '#f4f3f9', color: '#606266' }"
      border
      v-loading="loading"
      :data="equipmentList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column align="center" type="selection" width="50"/> -->
      <el-table-column align="center" label="设备ID" prop="equipmentID" />
      <el-table-column
        align="center"
        label="硬件号"
        prop="hardwareNumber"
        min-width="120px"
      />
      <el-table-column
        align="center"
        label="协议地址"
        prop="protocolAddress"
        min-width="120px"
      >
        <template slot-scope="scope">
          {{ scope.row.protocolAddress ? scope.row.protocolAddress : "--" }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="链接机台"
        prop="machineName"
        min-width="150px"
      >
        <template slot-scope="scope">
          {{ scope.row.machineName ? scope.row.machineName : "未链接" }}
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="运营模式" prop="mode" /> -->
      <el-table-column align="center" label="座位号" prop="seatNumber" />
      <el-table-column align="center" label="版本号" prop="vision" />
      <el-table-column
        align="center"
        label="最后断开时间"
        prop="lastTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.lastTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="创建人"
        prop="createdBy"
        min-width="120px"
      />
      <el-table-column
        align="center"
        :sort-orders="['descending', 'ascending']"
        :sortable="true"
        label="创建时间"
        prop="createdTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.createdTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="更新人"
        prop="updatedBy"
        min-width="120px"
      >
        <template slot-scope="scope">
          {{ scope.row.updatedBy === null ? "暂无" : scope.row.updatedBy }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :sort-orders="['descending', 'ascending']"
        :sortable="true"
        label="更新时间"
        prop="updatedTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.updatedTime === null
              ? "暂无"
              : parseTime(scope.row.updatedTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        label="操作"
        width="180"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.machineId == '0'"
            icon="el-icon-view"
            size="mini"
            type="text"
            style="color: red"
            @click="fum_getNoUseList(scope.row)"
            >绑定
          </el-button>
          <el-button
            v-else
            icon="el-icon-view"
            size="mini"
            type="text"
            style="color: green"
            @click="fun_untie(scope.row)"
            >解绑
          </el-button>
          <el-button
            v-hasPermi="['machine:equipment:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            >修改
          </el-button>
          <el-button
            v-hasPermi="['machine:equipment:remove']"
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改设备列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="硬件号" prop="hardwareNumber">
          <el-input v-model="form.hardwareNumber" placeholder="请输入硬件号" />
        </el-form-item>
        <el-form-item label="协议地址" prop="protocolAddress">
          <el-input
            v-model="form.protocolAddress"
            placeholder="请输入协议地址"
          />
        </el-form-item>
        <el-form-item label="门店" prop="status">
          <el-select
            v-model="form.storeId"
            placeholder="请选择门店进行添加"
            style="width: 100%"
          >
            <el-option
              v-for="item in storeOptions"
              :key="item.storeId"
              :label="item.storeName"
              :value="item.storeId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="链接状态" prop="status">
          <el-select
            v-model="form.status"
            placeholder="请选择链接状态"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in ['正常', '维护', '断开']"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本号" prop="vision">
          <el-input v-model="form.vision" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="最后断开" prop="lastTime">
          <el-date-picker
            v-model="form.lastTime"
            clearable
            placeholder="请选择最后断开"
            type="date"
            value-format="yyyy-MM-dd hh:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button
          type="primary"
          v-if="title !== '修改设备列表'"
          style="background-color: green"
          @click="continueSubmit"
          >保存&继续新增</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 绑定机台 -->
    <el-dialog
      :title="title"
      :visible.sync="open2"
      append-to-body
      width="500px"
    >
      <el-form
        ref="machine_board"
        :model="machine_board"
        :rules="machine_board_rules"
        label-width="80px"
      >
        <el-form-item label="绑定机台" prop="equipmentID">
          <el-select v-model="machine_board.machineID" placeholder="请选择机台" @change="handleMachineChange">
            <el-option
              v-for="item in no_machine"
              :key="item.machineID"
              :label="item.machineName"
              :value="item.machineID"
            >
              <span style="float: left">{{ item.machineName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="位置选择" v-if="showSeatSelection">
          <el-radio-group v-model="machine_board.seatNumber">
            <el-radio :label="1">位置1</el-radio>
            <el-radio :label="2">位置2</el-radio>
            <el-radio :label="3">位置3</el-radio>
            <el-radio :label="4">位置4</el-radio>
            <el-radio :label="5">位置5</el-radio>
            <el-radio :label="6">位置6</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="fun_bindings">确 定</el-button>
        <el-button @click="machine_cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addEquipment,
  delEquipment,
  getEquipment,
  listEquipment,
  updateEquipment,
  getAllStoreNameID,
  bindEquipment,
  unbindEquipment,
  getAllUseList,
} from "@/api/machine/equipment";

export default {
  name: "Equipment",
  data() {
    return {
      // 新增时用户的信息
      userId: sessionStorage.getItem("userId"),
      deptId: sessionStorage.getItem("deptId"),
      // pickerOptions: {
      //     shortcuts: [{
      //         text: '最近一周',
      //         onClick(picker) {
      //             const end = new Date();
      //             const start = new Date();
      //             start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      //             picker.$emit('pick', [start, end]);
      //         }
      //     }, {
      //         text: '最近一个月',
      //         onClick(picker) {
      //             const end = new Date();
      //             const start = new Date();
      //             start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      //             picker.$emit('pick', [start, end]);
      //         }
      //     }, {
      //         text: '最近三个月',
      //         onClick(picker) {
      //             const end = new Date();
      //             const start = new Date();
      //             start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      //             picker.$emit('pick', [start, end]);
      //         }
      //     }]
      // },
      // 所有门店信息
      storeOptions: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备列表表格数据
      equipmentList: [],
      // 弹出层标题
      title: "",
      // 日期范围
      dateRange: [],
      // 是否显示弹出层
      open: false,
      // 是否显示绑定机台弹窗
      open2: false,
      // 未绑定机台的拉框
      no_machine: [],
      // 要进行绑定的板子
      machine_board: {
        machineID: null,
        equipmentID: null,
        seatNumber: 1
      },
      // 是否显示位置选择
      showSeatSelection: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentID: null,
        hardwareNumber: null,
        status: null,
        lastTime: null,
        // testTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        hardwareNumber: [
          { required: true, message: "硬件号不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "链接状态不能为空", trigger: "change" },
        ],
        // mode: [
        //   { required: true, message: "运营模式不能为空", trigger: "blur" },
        //   // { pattern: /^\d+$/, message: "运营模式应该为数值类型", trigger: "blur" }
        // ],
        vision: [
          { required: true, message: "版本号不能为空", trigger: "blur" },
        ],
        lastTime: [
          { required: true, message: "最后断开不能为空", trigger: "blur" },
        ],
        protocolAddress: [
          { required: true, message: "协议地址不能为空", trigger: "blur" },
        ],
      },
      // 绑定板子表单检验
      machine_board_rules: {
        machineID: [
          { required: true, message: "机台不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getAllStoreNameID();
  },
  methods: {
    /** 查询设备列表列表 */
    getList() {
      this.loading = true;
      listEquipment(this.queryParams).then((response) => {
        this.equipmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 查询门店
    getAllStoreNameID() {
      // //console.log('执行了');
      getAllStoreNameID().then((response) => {
        this.storeOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 表单重置
    reset() {
      // 获取当前时间
      var year = new Date().getFullYear();
      var month = (1 + new Date().getMonth()).toString().padStart(2, "0");
      var day = new Date().getDate().toString().padStart(2, "0");
      var hours = new Date().getHours().toString().padStart(2, "0");
      var minutes = new Date().getMinutes().toString().padStart(2, "0");
      var seconds = new Date().getSeconds().toString().padStart(2, "0");

      let timer = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      //console.log(timer);

      this.form = {
        // equipmentID: null,
        hardwareNumber: null,
        status: "断开",
        // mode: '链接中',
        vision: "1.0",
        lastTime: timer,
        protocolAddress: "",
        // isDelete: null,
        // createdBy: null,
        // createdTime: null,
        // updatedBy: null,
        // updatedTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // this.queryParams.pageNum = 1;
      // 增加时间
      if (this.dateRange) {
        this.queryParams.beginTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = null;
      this.queryParams.storeName = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.equipmentID);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备列表";
    },
    // 快速新增
    rapidAdd() {
      // this.reset();
      if (this.form.hardwareNumber) {
        this.form.hardwareNumber = null;
      }
      this.open = true;
      this.title = "快速添加设备列表";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const equipmentID = row.equipmentID || this.ids;
      getEquipment(equipmentID).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备列表";
      });
    },
    // 获取未绑定的机台
    fum_getNoUseList(row) {
      this.machine_board = {
        machineID: null,
        equipmentID: null,
        seatNumber: 1
      };
      this.showSeatSelection = false;
      this.machine_board.equipmentID = row.equipmentID;
      // 获取点击的对象
      getAllUseList().then((response) => {
        console.log('获取所有的机台:', response);
        this.no_machine = response.rows;
        this.title = "绑定机台";
        this.open2 = true;
      });
      // // 获取点击的对象
      // getNoUseList().then((response) => {
      //   // console.log('获取未绑定的机台:', response);
      //   this.no_machine = response.rows;
      //   this.title = "绑定机台";
      //   this.open2 = true;
      // });
    },
    // 绑定机台
    fun_bindings() {
      this.$refs["machine_board"].validate((valid) => {
        if (valid) {
          if (this.machine_board.machineID != null) {
            bindEquipment(this.machine_board).then((response) => {
              this.$modal.msgSuccess("绑定成功");
              this.open2 = false;
              this.machine_board = {
                machineID: null,
                equipmentID: null,
                seatNumber: 1
              };
              this.showSeatSelection = false;
              this.getList();
            });
          }
        }
      });
    },
    // 监听机台选择变化
    handleMachineChange(machineID) {
      // 根据选择的机台ID查找对应的机台对象
      const selectedMachine = this.no_machine.find(item => item.machineID === machineID);
      // 判断是否显示位置选择
      this.showSeatSelection = selectedMachine && selectedMachine.typeID === 4;
      // 如果不需要显示位置选择，重置seatNumber为null
      // 默认选择位置1
      this.machine_board.seatNumber = 1;
    },
    // 取消绑定
    fun_untie(row) {
      console.log(row);
      this.machine_board.machineID = row.machineId;
      this.machine_board.equipmentID = row.equipmentID;
      this.$modal
        .confirm('是否确认解开板子ID为"' + row.equipmentID + '"的板子？')
        .then(() => {
          return unbindEquipment(this.machine_board);
        })
        .then(() => {
          this.getList();
          this.open2 = false;
          this.$modal.msgSuccess("解绑成功");
        })
        .catch(() => {});
    },

    machine_cancel() {
      this.open2 = false;
      this.machine_board = {
        machineID: null,
        equipmentID: null,
        seatNumber: 1
      };
      this.showSeatSelection = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.equipmentID != null) {
            this.form.updatedBy = this.$store.state.user.name;
            updateEquipment(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.createdBy = this.$store.state.user.name;
            this.form.userId = this.userId;
            this.form.deptId = this.deptId;
            addEquipment(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 提交后继续新增
    continueSubmit() {
      console.log('进行快速新增');
      this.open = false;
      // 新增必加参数
      this.form.createdBy = this.$store.state.user.name;
      this.form.userId = this.userId;
      this.form.deptId = this.deptId;
      addEquipment(this.form).then((response) => {
        this.$modal.msgSuccess("新增成功");
        // 去除硬件号的值
        this.form.hardwareNumber = null;
        this.open = true;
        this.getList();
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const equipmentIDs = row.equipmentID || this.ids;
      //console.log('是否确认删除设备列表编号为"' + equipmentIDs + '"的数据项？');
      this.$modal
        .confirm('是否确认删除设备列表编号为"' + equipmentIDs + '"的数据项？')
        .then(function () {
          return delEquipment(equipmentIDs);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 日志按钮操作 */
    handleSeeLog(row) {
      this.$router.push({
        path: "/machine/log",
        query: { equipmentID: row.equipmentID },
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "machine/equipment/export",
        {
          ...this.queryParams,
        },
        `equipment_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
